const cli = require('cac')()
// const { SyncHook } = require('./tapable')
const { SyncHook, SyncBailHook, SyncLoopHook, AsyncParallelHook } = require('tapable')

cli
  .option('--type <type>', '要执行的钩子模块案例', {
    default: 'SyncHook',
  })

  cli.help()

  const parsed = cli.parse()
  // console.log(JSON.stringify(parsed, null, 2))
  const parsedOption = parsed.options

  // TODO 案例不完整，之后如果用到可以补充完整
  switch (parsedOption.type) {
    case 'SyncHook':
      syncHook(SyncHook)
    break;
    case 'SyncLoopHook':
      syncHook(SyncLoopHook)
    break;
    case 'SyncBailHook':
      syncHook(SyncBailHook)
    break;
    case 'AsyncHook':
      asyncHook(AsyncHook)
    break;
    case 'AsyncLoopHook':
      asyncHook(AsyncLoopHook)
    break;
    case 'AsyncParallelHook':
      asyncHook(AsyncParallelHook)
    break;
    default:
      syncHook(SyncHook)
  }
  
// 同步钩子的调用 demo
function syncHook(HookModule) {
  // 普通同步钩子
  const hook = HookModule(['name', 'age'])

  hook.tap('fn1', function(name, age) {
    console.log('fn1', name, age)
  })

  hook.tap('fn2', function(name, age) {
    console.log('fn2', name, age)
  })

  hook.call('nvp', 28)
}

// 异步钩子调用 demo
function asyncHook(HookModule) {
  const hook = HookModule(['name', 'age'])

  hook.tapAsync('fn1', function(name, age, callback) {
    setTimeout(() => {
      console.log('fn1', name, age)
      callback('这里是fn1')
    }, 4000)
  })

  hook.tapAsync('fn2', function(name, age, callback) {
    setTimeout(() => {
      console.log('fn2', name, age)
      callback()
    }, 2000)
  })

  hook.callAsync('nvp', 28, (data) => {
    console.log('结束', data)
  })
}

